import { tokenStore } from "@/stores/tokenStore";
import { HttpType } from "../TsEnums";
import { AjaxOption } from "../Types";
import axios from "axios";

class ApiCore {
    /**
     * 请求Token
     * @param username 用户名
     * @param password 密码
     * @param options 参数
     * @param clientID 客户端标识ID
     * @param baseUrl Api主机地址
     */
    public static CallOAuth2Token(username: string, password: string, options: AjaxOption, clientID: string = Config._CLIENT_ID, baseUrl: string = Config._API_URL): void {
        let opts: AjaxOption = {
            url: `${baseUrl}/token`,
            method: HttpType.POST,
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                Authorization: "Basic " + btoa(clientID + ":"),
            },
            data: "username=" + username + "&password=" + password + "&grant_type=password",
            timeout: 10000,
        };

        MergeObjs(opts, options);

        axios(opts)
            .then((res) => {
                opts.success && opts.success(res.data);
            })
            .catch((err) => {
                opts.error && opts.error(err);
            });
    }

    /**
     * 刷新Token
     * @param options 参数
     * @param clientID 客户端标识ID
     * @param baseUrl Api主机地址
     */
    public static CallOAuth2RefreshToken(options: AjaxOption, clientID: string = Config._CLIENT_ID, baseUrl: string = Config._API_URL): void {
        let _token = tokenStore().token;

        let opts: AjaxOption = {
            url: baseUrl + "/token",
            method: HttpType.POST,
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                Authorization: "Basic " + btoa(clientID + ":"),
            },
            data: "refresh_token=" + _token.refresh_token + "&grant_type=refresh_token",
            timeout: 10000,
        };

        MergeObjs(opts, options);

        axios(opts)
            .then((res) => {
                opts.success && opts.success(res.data);
            })
            .catch((err) => {
                opts.error && opts.error(err);
            });
    }

    public static CallJwtToken(loginCode: string, username: string, password: string, options: AjaxOption, clientID: string = Config._CLIENT_ID, baseUrl: string = Config._API_URL): void {
        let opts: AjaxOption = {
            url: `${baseUrl}/token`,
            method: HttpType.POST,
            headers: {
                "Content-Type": "application/json",
                clientID: "Basic " + btoa(clientID + ":"),
            },
            data: {
                loginCode: loginCode,
                loginName: username,
                password: password,
            },
            timeout: 10000,
        };

        MergeObjs(opts, options);

        axios(opts)
            .then((res) => {
                opts.success && opts.success(res.data);
                opts.complete && opts.complete();
            })
            .catch((err) => {
                opts.error && opts.error(err);
                opts.complete && opts.complete();
            });
    }

    /**
     * 请求Api
     * @param options 参数
     * @returns
     */
    public static Call(options: AjaxOption): Promise<any> {
        let _token = tokenStore().token;

        let opts: AjaxOption = {
            url: "",
            timeout: Config._AJAX_TIMEOUT,
            headers: {},
        };

        MergeObjs(opts, options);

        //如果需要token且token有值，则添加到请求头
        if (opts.hasToken && !Gx.IsEmpty(_token)) {
            MergeObjs(opts.headers, { Authorization: "Bearer " + _token.access_token });
        }

        return axios(opts)
            .then((res) => {
                opts.success && opts.success(res.data);
                opts.complete && opts.complete();
                return Promise.resolve(res.data.data);
            })
            .catch((res) => {
                opts.error && opts.error(res);
                opts.complete && opts.complete();
                return Promise.reject(res);
            });
    }
}

export default ApiCore;
